<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.documentWorkPlace.importSet')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="350"
      :width="600"
    >
      <BasicForm @register="registerForm">
        <template #menu="{ model, field }">
          <BasicUpload
            v-model:value="model[field]"
            :maxSize="50"
            :maxNumber="10"
            :api="uploadFileApi"
          />
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getImportForm } from './tableData';
  import { importFile, UploadFolderFileByFolders } from '/@/api/demo/document';
  import { BasicUpload } from '/@/components/Upload';
  import { uploadFileApi } from '/@/api/sys/upload';

  const emit = defineEmits(['register', 'success']);

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const FolderId = ref<string>('');

  // 提交
  async function handleSubmit() {
    try {
      const res = await validate();
      setModalProps({ confirmLoading: true });
      const { DocType, selectType, DhType, files } = res;
      let uploadResult = false;

      if (selectType === '1') {
        uploadResult = await importFile(DocType, DhType, FolderId.value, files);
      } else if (selectType === '2') {
        uploadResult = await UploadFolderFileByFolders(DocType, DhType, FolderId.value, files);
      }

      if (uploadResult) {
        handleSuccess();
      }
    } catch (error) {
      createMessage.error('导入失败，请重试');
      console.error(error);
    }
  }

  function handleSuccess() {
    createMessage.success('导入成功');
    handleCancel();
    emit('success');
  }

  const handleCancel = () => {
    closeModal();
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    FolderId.value = data.treeKey;
    resetFields();
    setModalProps({ confirmLoading: false });
    updateSchema({
      field: 'DocType',
      componentProps: {
        options: data.docType,
      },
    });
  });

  // 初始化表格
  const [registerForm, { resetFields, validate, updateSchema }] = useForm({
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
    schemas: getImportForm(),
    showActionButtonGroup: false,
  });
</script>
